const state = {
    cartList: JSON.parse(uni.getStorageSync('cartList') || '[]')
}

const mutations = {
    // 添加商品到购物车
    addToCart(state, goods) {
        const findResult = state.cartList.find(item => item.goods_id === goods.goods_id)
        if (!findResult) {
            state.cartList.push(goods)
        } else {
            findResult.goods_count++
        }
        this.commit('cart/saveSetStorage')
    },
    // 持久化到本地
    saveSetStorage(state) {
        uni.setStorageSync('cartList', JSON.stringify(state.cartList))
    },

    // 更新商品状态
    updateGoodsState(state, goods) {
        const findResult = state.cartList.find(item => item.goods_id === goods.goods_id)
        if (findResult) {
            findResult.goods_state = goods.goods_state
            this.commit('cart/saveSetStorage')
        }
    },

    // 更新商品数量
    updateGoodsCount(state, goods) {
        const findResult = state.cartList.find(item => item.goods_id === goods.goods_id)
        if (findResult) {
            findResult.goods_count = goods.goods_count
            this.commit('cart/saveSetStorage')
        }
    },

    //根据商品id删除商品
    deleteGoodsById(state,goods_id){
        state.cartList = state.cartList.filter(item => item.goods_id !== goods_id)
        this.commit('cart/saveSetStorage')
    },

    // 更新购物车所有商品的状态
    updateAllGoodsState(state,newState){
        state.cartList.forEach(item => item.goods_state = newState)
        this.commit('cart/saveSetStorage')
    }
}

const actions = {}

const getters = {
    // 购物车商品总数量
    total(state) {
        let count = 0
        state.cartList.forEach(item => count += item.goods_count)
        return count
    },
    // 购物车已勾选商品的总数量
    checkedCount(state){
        return state.cartList.filter(item => item.goods_state).reduce((total,item) => total += item.goods_count, 0)
    },
    // 购物车已勾选商品的总价格
    checkedTotalPrice(state){
        return state.cartList.filter(item => item.goods_state).reduce((total,item) => total += (item.goods_price * item.goods_count), 0)
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}


